#include "logger.h"

// 获取日志的单例
Logger& Logger::getInstance()
{
    static Logger logger;
    return logger;
}

Logger::Logger()
{
    // 启动一个专门写日志的线程
    std::thread writeLog([&](){
        while(true)
        {
            // 获取当天的日期，然后去日志信息，写入到响应的日志文件中
            time_t now = time(nullptr);
            struct tm* nowTime = localtime(&now);

            char fileName[128];
            snprintf(fileName, 128, "%d-%d-%d-log.txt", nowTime->tm_year + 1900, nowTime->tm_mon + 1, nowTime->tm_mday);

            FILE* pf = fopen(fileName, "a+");
            if(pf == nullptr)
            {
                std::cout << "logger file: " << fileName << " open error!" << std::endl;
                exit(EXIT_FAILURE); 
            }

            std::string msg;
            _lockQueue.Pop(&msg);

            char timeBuf[32] = {0};
            snprintf(timeBuf, 32, "%d:%d:%d ==> [%s] ", nowTime->tm_hour, nowTime->tm_min, 
                    nowTime->tm_sec, _logLevel == INFO ? "INFO" : "ERROR");
            msg.insert(0, timeBuf);
            msg.push_back('\n');
            fputs(msg.c_str(), pf);
            fclose(pf);
        }
    });
    // 设置分离线程
    writeLog.detach();
}

// 设置日志级别
void Logger::setLogLevel(LogLevel level)
{
    _logLevel = level;
}

// 写日志，将日志信息写入到_lockQueue缓冲区中
void Logger::Log(std::string msg)
{
    _lockQueue.Push(msg);
}